package com.tim.helper.class_parse;

import org.junit.Test;

import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;

public class ClassParser {


    /**
     * java路径，转为class对象路径
     * 读取、解析
     */
    @Test
    public void parse() throws Exception{
    String path =
        "E:\\gitlab\\xqxc\\plat\\plat-merchant\\plat-merchant-impl\\src\\main\\java\\com\\xqxc\\api\\impl\\plat\\merchant\\mq\\MerchantMessageListener.java" +
                "";
        parse(path);
    }

    public void parse(String path) throws Exception {
        // 转为class对象路径
        path = path.trim()
                .replace("\\src\\main\\java", "\\target\\classes")
                .replaceAll("java$", "class");
        System.out.println(path);
        String[] infos = path.split("\\\\target\\\\classes\\\\");

        String classFullName = infos[1].replaceAll("\\.class$", "")
                .replaceAll("[/\\\\]+", ".");
        Class cls = loadFileClass(infos[0]+"/target/classes/", classFullName);

        System.out.println(cls);

        Field[] fields = cls.getDeclaredFields();
        for(Field field : fields){
            field.setAccessible(true);
            Annotation[] annotations = field.getAnnotations();
            if(annotations.length>0){
                System.out.println(Arrays.toString(annotations));
            }
            System.out.println(field.toString().replace(classFullName+".", ""));
        }

        Method[] methods = cls.getMethods();
        for(Method method : methods){
            Annotation[] annotations = method.getAnnotations();
            if(annotations.length>0){
                System.out.println(Arrays.toString(annotations));
            }
            System.out.println(method.toString().replace(classFullName+".", ""));
        }
    }

    // https://www.jianshu.com/p/c11fb8da30b5
    public Class loadFileClass(String directory, String classFullName) throws MalformedURLException, ClassNotFoundException {
        // Create a File object on the root of the directory containing the class file
        URL url = new File(directory).toURI().toURL();          // file:/c:/myclasses/
        URL[] urls = new URL[]{url};

        // Create a new class loader with the directory
        ClassLoader cl = new URLClassLoader(urls);

        // Load in the class; MyClass.class should be located in
        // the directory file:/c:/myclasses/com/mycompany
        Class cls = cl.loadClass(classFullName);

        return cls;
    }
}
